package com.seanbot.armstrong.rc4cipher;

import java.io.UnsupportedEncodingException;

import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class RC4cipher extends Activity {
	EditText key = null;
	TextView stream = null;
	CipherAlgorithm ca = null;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rc4cipher);

		key = (EditText) findViewById(R.id.editTextKey);
		stream = (TextView) findViewById(R.id.textViewStream);
		Button nextButton = (Button) findViewById(R.id.buttonNext);

		// Add listeners to the editTextKey field
		key.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				try {
					stream.setText("");
					key = (EditText) findViewById(R.id.editTextKey);
					String keyStr = key.getText().toString();
					createNewCipherAlg(keyStr);
					ca.createStream();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		});

		nextButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				try {
					stream.setText((stream.getText() + ca.getStreamNext())
							.toUpperCase());
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_rc4cipher, menu);
		return true;
	}

	public void createNewCipherAlg(String key)
			throws UnsupportedEncodingException {
		ca = new CipherAlgorithm(key);
	}
}
